package com.example.mybatisplusdemo.web.controller;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.mybatisplusdemo.common.utls.SessionUtils;
import com.example.mybatisplusdemo.model.domain.User;
import com.example.mybatisplusdemo.model.dto.UserCartProductDTO;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.RequestMapping;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.example.mybatisplusdemo.common.JsonResponse;
import com.example.mybatisplusdemo.service.ICartService;
import com.example.mybatisplusdemo.model.domain.Cart;

import javax.xml.transform.Result;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;


/**
 *
 *  前端控制器
 *
 *
 * @author lqj
 * @since 2025-06-30
 * @version v1.0
 */
@RestController
@RequestMapping("/api/cart")
public class CartController {

    private final Logger logger = LoggerFactory.getLogger( CartController.class );

    @Autowired
    private ICartService cartService;


    /**
    * 描述：根据Id 查询
    *
    */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public JsonResponse<Cart> getById(@PathVariable("id") Long id)throws Exception {
        Cart cart = cartService.getById(id);
        return JsonResponse.success(cart);
    }

    @GetMapping("/list")
    public JsonResponse<List<UserCartProductDTO>> getCartList(@RequestParam Long userId) {
        List<UserCartProductDTO> list = cartService.getCartByUserId(userId);
        return JsonResponse.success(list);
    }

    @PutMapping("/updateQuantity")
    @ResponseBody
    public JsonResponse<?> updateQuantity(@RequestBody Map<String, Object> payload) {
        Long cartId = Long.valueOf(payload.get("cartId").toString());
        BigDecimal quantity = new BigDecimal(payload.get("quantity").toString());

        Cart cart = cartService.getById(cartId);
        if (cart == null || cart.getDeleted()) {
            return JsonResponse.failure("购物车商品不存在或已删除");
        }

        cart.setQuantity(quantity);
        cart.setUpdateTime(LocalDateTime.now());
        cartService.updateById(cart);

        return JsonResponse.success("更新成功");
    }

    @DeleteMapping("/delete/{id}")
    @ResponseBody
    public JsonResponse<?> deleteCart(@PathVariable("id") Long id) {
        // 使用 UpdateWrapper 确保更新 is_deleted 字段
        UpdateWrapper<Cart> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("is_deleted", true)
                .set("update_time", LocalDateTime.now())
                .eq("id", id)
                .eq("is_deleted", false); // 只更新未删除的记录

        boolean success = cartService.update(updateWrapper);

        if (success) {
            logger.info("成功删除购物车项: {}", id);
            return JsonResponse.success("删除成功");
        } else {
            logger.warn("删除购物车项失败: {}", id);
            return JsonResponse.failure("删除失败，可能已被删除");
        }
    }

    @PostMapping("/add")
    public JsonResponse<?> addToCart(
            @RequestParam("productId") Long productId,
            @RequestParam("quantity") BigDecimal quantity) {

        // ✅ 从工具类中获取当前登录用户
        User user = SessionUtils.getCurrentUserInfo();
        if (user == null || user.getId() == null) {
            return JsonResponse.failure("请先登录");
        }
        Long userId = user.getId();

        // ✅ 构造更新条件
        UpdateWrapper<Cart> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_id", userId)
                .eq("product_id", productId)
                .eq("is_deleted", false)
                .setSql("quantity = quantity + " + quantity)
                .set("update_time", LocalDateTime.now());

        boolean updated = cartService.update(updateWrapper);

        // ✅ 如果更新失败（说明没有记录），则新增一条
        if (!updated) {
            Cart newCart = new Cart();
            newCart.setUserId(userId);
            newCart.setProductId(productId);
            newCart.setQuantity(quantity);
            newCart.setDeleted(false);
            newCart.setCreateTime(LocalDateTime.now());
            newCart.setUpdateTime(LocalDateTime.now());

            boolean saved = cartService.save(newCart);
            if (saved) {
                logger.info("新增购物车项成功 - 用户ID: {}, 商品ID: {}", userId, productId);
                return JsonResponse.success("添加成功");
            } else {
                logger.error("新增购物车项失败 - 用户ID: {}, 商品ID: {}", userId, productId);
                return JsonResponse.failure("添加失败");
            }
        }

        logger.info("更新购物车项成功 - 用户ID: {}, 商品ID: {}", userId, productId);
        return JsonResponse.success("添加成功");
    }



}

